/**
 * Mock Request Listener
 * @author Wangtd
 */
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const moment = require('moment');
const JSON5 = require('json5');

function Mocker() {}
Mocker.prototype.mock = function(dirname) {
    return function(request, response, next) {
        var hasExt = false;
        var urlObj = url.parse(request.url, true);
        var pathName = urlObj.pathname;
        var isOriginal = urlObj.query && urlObj.query['origin'];

        pathName = decodeURI(pathName);

        var extName = path.extname(pathName);

        if (extName === '') {
            if (pathName.charAt(pathName.length - 1) !== '/') {
                var baseName = path.basename(pathName);
                if (baseName.indexOf('.') === 0) {
                    // when file name is empty
                    extName = baseName;
                } else {
                    // when extension is empty
                    extName = '.json'
                    pathName += extName;
                }
                hasExt = true;
            }
        } else {
            hasExt = true;
        }

        var filePath = path.join(path.join(__dirname, dirname), pathName);

        fs.exists(filePath, function(exists) {
            if (exists) {
                if (hasExt) {
                    try {
                        var data = fs.readFileSync(filePath, 'utf8');
                        if (isOriginal || extName !== '.json') {
                            response.writeHead(200, {
                                'content-type': 'text/plain;charset=utf-8'
                            });
                        } else {
                            data = JSON.stringify(JSON5.parse(data));
                            response.writeHead(200, {
                                'content-type': 'application/json;charset=utf-8'
                            });
                        }
                        response.end(data);
                    } catch (e) {
                        console.error(e);
                        response.writeHead(500, { 'content-type': 'text/html' });
                        response.end('<h1>500 Server Error: </h1><pre>' + e + '</pre>');
                    }
                } else {
                    var html = '';
                    try {
                        var indexName = pathName;
                        if (pathName !== '/') {
                            indexName = pathName.substring(0, pathName.lastIndexOf('/'));
                        }

                        html =  '<html lang="zh-CN">';
                        html += '<head>';
                        html += '<meta charset="utf-8">';
                        html += '<link rel="icon" href="/app/imgs/favicon.ico">';
                        html += '<title>Index of ' + indexName + '</title>';
                        // font style
                        html += '<style>body{font-family:"Trebuchet MS",verdana,lucida,arial,helvetica,sans-serif;}</style>';
                        html += '</head>';

                        html += '<body>';
                        html += '<h1>Index of ' + indexName + '</h1>';
                        html += '<table cellspacing="10">';
                        html += '<tr><th align="left">Name</th><th>Last Modified</th><th>Size</th><th>Description</th></tr>';
                        html += '<tr><td><a href="../">Parent Directory</a></td></tr>';

                        // list files
                        var filedir = filePath.substring(0, filePath.lastIndexOf(path.sep));
                        var files = fs.readdirSync(filedir);
                        for (var i in files) {
                            var filename = files[i];
                            var link = filename, size = '';
                            var stat = fs.statSync(path.join(filedir, filename));
                            if(stat.isDirectory()) {
                                link += '/';
                            } else {
                                size = stat.size;
                            }
                            html += '<tr><td><a href="' + link + '">' + link + '</a></td><td>'
                                 + moment(stat.mtime).format('ddd MMM DD HH:mm:ss [CST] YYYY') + '</td><td align="right">'
                                 + size +'</td></tr>';
                        }

                        html += '</table>';
                        html += '</body>';
                        html += '</html>';
                    } catch (e) {
                        console.error(e);
                        html =  '<h1>List File Error: </h1>';
                        html += '<pre>' + e + '</pre>';
                    }

                    response.writeHead(200, { 'content-type': 'text/html' });
                    response.end(html);
                }
            } else {
                response.writeHead(404, { 'content-type': 'text/html' });
                response.end('<h1>404 Not Found</h1>');
            }
        });
    };
}

module.exports.listen = new Mocker().mock;
